import sys,os
import subprocess
try:
    import PyQt5
except ImportError:
    print('can\'t find pyqt5! exit')
    sys.exit(-1)

ppath = PyQt5.__path__
if isinstance(ppath, list) and len(ppath) > 0:
    ppath = ppath[0]
else:
    print('pyqt5 path error! ')
    sys.exit(-1)

p = subprocess.Popen(['apt','list'], stdout=subprocess.PIPE)

is_found = False

for tl in p.stdout.read().decode().split('\n'):
    if tl.split('/')[0] == 'extra-cmake-modules':
        is_found = True
if not is_found:
    print('需要安装 extra-cmake-modules，请手动执行:\n\tsudo apt install extra-cmake-modules')
    sys.exit(-1)

if not os.path.exists('fcitx-1t5'):
    os.system('git clone https://gitee.com/hocker/fcitx-qt5')

if not os.path.exists('fcitx-qt5/build'):
    os.system('mkdir fcitx-qt5/build')
build_cmd = '. ~/.bashrc && cd fcitx-qt5/build && cmake .. && make -j8'
ret = os.system(build_cmd)
# os.system('sudo make install')
copy_cmd= 'cp fcitx-qt5/build/platforminputcontext/libfcitxplatforminputcontextplugin.so  ' + os.path.join(ppath, 'Qt/plugins/platforminputcontexts/libfcitxplatforminputcontextplugin.so')
ret |= os.system(copy_cmd)

if ret != 0:
    print('自动执行失败,需手动执行') 
    print('手动执行:\n\t'+build_cmd ) # 'cd fcitx-qt5/build && cmake .. && make -j8 &&sudo make install '
    print('执行成功后，然后执行:\n\t ' +copy_cmd)

